package com.rchat.pocmini.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.airtalkee.sdk.entity.AirSession;
import com.aso.common.ble.BleManager;
import com.aso.common.ble.LeManager;
import com.aso.common.ble.callback.BleScanAndConnectCallback;
import com.aso.common.ble.data.BleDevice;
import com.aso.common.ble.exception.BleException;
import com.aso.common.ble.scan.BleScanRuleConfig;
import com.aso.common.bluetooth.BluetoothUtils;
import com.aso.common.bluetooth.bean.BluetoothDeviceBean;
import com.aso.common.sp.SPHelper;
import com.aso.common.utils.NetworkUtils;
import com.aso.common.utils.ToastUtils;
import com.aso.common.utils.TranslateUtils;
import com.aso.common.utils.Utils;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.PocApplication;
import com.rchat.pocmini.R;
import com.rchat.pocmini.bean2eventbus.BluetoothBean;
import com.rchat.pocmini.bean2eventbus.BTDeviceBean;
import com.rchat.pocmini.bean2eventbus.Talk2PttBean;
import com.rchat.pocmini.bean2eventbus.TalkBean;
import com.rchat.pocmini.bluetooth.gaiabyroen.Gaia;
import com.rchat.pocmini.bluetooth.gaiabyroen.GaiaCommand;
import com.rchat.pocmini.bluetooth.gaiabyroen.GaiaLink;
import com.rchat.pocmini.service.PocService;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.SPUtil;
import com.rchat.pocmini.util.Sound;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * Created by ljd on 2017/3/14.
 *
 * @modify sdf on 2017/8/12
 * 蓝牙外接设备
 * 注册监听蓝牙sco状态 : AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED
 */
public class BTService extends Service implements LeManager.IBlePTTCallback {
    private static final String TAG = "BTService";
    private static final String TAG_SCO = "Log_SCO";

//    /**
//     * ptt松开，sco延迟5关闭
//     */
//    private static final int SCO_STOP_DELAY_5_S = 5 * 1000;
//    private Handler mBluetoothScoHandler = new Handler();

    private GaiaLink mGaiaLink;
    private String mBlueToothAddress;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothHeadset mBluetoothHeadset = null;
    private BluetoothDevice mBluetoothDevice = null;

    public static BTService instance;

    private boolean isBtPttPress = false; // 是否是蓝牙ptt按下


    /**
     * Ble蓝牙设备是否搜索中
     */
    public boolean isBleScaning = false;

    /**
     * 当前PTT键功能是否可以使用
     * 如果连接的设备不在用户当前账号绑定的蓝牙设备中，则不允许使用PTT功能
     */
    private boolean isEnablePTT = false;

    public static BTService getInstance() {
        return instance;
    }

    private final IBinder mBinder = new LocalBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        instance = this;
        registerBtReceiver();
        init();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (null != mGaiaLinkReceiveHandler) {
            mGaiaLinkReceiveHandler.removeCallbacksAndMessages(null);
        }
        unregisterReceiver(mBluetoothReceiver);

        LeManager.getInstance().destory();
        super.onDestroy();
    }

    private void init() {
        initBluetooth();
        initOther();
    }

    /**
     * 初始化蓝牙相关
     */
    private void initBluetooth() {
//        BleManager.getInstance().init(Utils.getApplication());
//        onScanBle(this);
        LeManager.getInstance().init();
        String bleMac = SPHelper.getString(SPHelper.SPKeyGlobal.KEY_BLE_MAC);
//        String bleMac = (String) SPUtil.get(this, SPHelper.SPKeyGlobal.KEY_BLE_MAC, "C5:5E:D4:7B:55:55");
        LeManager.getInstance().onScanBleAndConnected(bleMac, this);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (null == mBluetoothAdapter) {
            ToastUtils.showToast(this, "当前设备蓝牙功能不可用！");
            return;
        }
        mGaiaLink = new GaiaLink(GaiaLink.Transport.BT_SPP);
        mGaiaLink.setReceiveHandler(mGaiaLinkReceiveHandler);
        if (mBluetoothAdapter.isEnabled()) {
            int headset = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            if (headset == BluetoothProfile.STATE_CONNECTED) {
                mBluetoothAdapter.getProfileProxy(getApplicationContext(), mProfileListener, BluetoothProfile.HEADSET);
            }
        }
    }

    /**
     * 初始化其他相关
     */
    private void initOther() {
    }

    /**
     * 注册蓝牙检测广播
     */
    private void registerBtReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        //蓝牙开关状态的广播
//        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        //蓝牙连接状态的广播
        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        //注册监听蓝牙sco状态
        intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        // 发现搜索到的设备
//        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBluetoothReceiver, intentFilter);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBluetoothEventBus(BluetoothBean bean) {
        ALog.dTag(TAG, "CurrentEvent = %s", bean.getCurrentEvent());
        if (!bean.isTarget(this.getClass())) {
            return;
        }
        switch (bean.getCurrentEvent()) {
            case BluetoothBean.EVENT_CONNECT:
            case BluetoothBean.EVENT_CHANGECONNECT:
                mBlueToothAddress = bean.getAddress();
                ALog.dTag(TAG, "bluetooth isEnable = %s,mBlueToothAddress = %s", mBluetoothAdapter.isEnabled(), mBlueToothAddress);
                if (mBluetoothAdapter.isEnabled()) {
                    if (mBluetoothAdapter.isDiscovering()) {
                        mBluetoothAdapter.cancelDiscovery();
                    }
                    mBluetoothAdapter.startDiscovery();
                } else {
                    mBluetoothAdapter.enable();
                }
                break;
            case BluetoothBean.EVENT_DISCONNECT:
                break;
            case BluetoothBean.EVENT_BIND:
                isEnablePTT = bean.isBind();
                connectPTT(bean.getAddress());
                break;
            case BluetoothBean.EVENT_UNBIND:
                isEnablePTT = bean.isBind();
                disconnectPTT();
                break;
            case BluetoothBean.EVENT_PTT_DOWN:
                pttTalkNormal(true);
                break;
            case BluetoothBean.EVENT_PTT_UP:
                pttTalkNormal(false);
                break;
            case BluetoothBean.EVENT_ENABLE_PTT:
                isEnablePTT = ((int) SPUtil.get(this, SPUtil.SPKeyGlobal.KEY_IS_ENABLEPTT, 0) == 1) ? true : false;
                ToastUtils.showToast(this, TranslateUtils.getEnablePttTip(isEnablePTT));
                break;
            default:
                break;
        }


    }

    /**
     * PocService.java中发出的，用于处理对讲申请与结束、申请时有冲突与结束等事件处理
     *
     * @param result
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusTalkStatus(Talk2PttBean result) {
        if (result == null || !result.isTarget(this.getClass())) {
            return;
        }
        ALog.dTag(TAG, "getCurrentEvent = %s", result.getCurrentEvent());
        //判断是否是ble调起的
        if (Talk2PttBean.EVENT_BLE_TALK == result.getCurrentEvent()) {
            //ble 调起sdk讲话
            pttHandleTalk(true);
        } else if (Talk2PttBean.EVENT_BLE_TALK_RELEASE == result.getCurrentEvent()) {
            //ble 释放SDK讲话
            pttHandleTalk(false);
        } else if (Talk2PttBean.EVENT_OPEN_SCO == result.getCurrentEvent()) {
            startBluetoothScoOn();
        } else if (Talk2PttBean.EVENT_CLOSE_SCO == result.getCurrentEvent()) {
            stopBluetoothScoOn();
        } else {

        }
    }

    /**
     * 发起蓝牙SCO通道的建立连接（连接过程是耗时的），在连接成功后打开SCO通道
     */
    public void startBluetoothScoOn() {
        if (PocApplication.getInstance().getConnectionState() == BluetoothProfile.STATE_CONNECTED) {
            PocApplication.getInstance().mAudioManager.setMode(AudioManager.MODE_IN_CALL); //这边要记得设置这个通讯模式，不然声音会从手机出来
            ALog.dTag(TAG_SCO, "发起了SCO通道建立:isBluetoothScoOn = %s", PocApplication.getInstance().mAudioManager.isBluetoothScoOn());
            if (!PocApplication.getInstance().mAudioManager.isBluetoothScoOn()) {
                PocService.getInstance().setBluetoothScoOn(false);
                PocApplication.getInstance().mAudioManager.startBluetoothSco();
            }
        }
    }

    /**
     * 关闭SCO通道并断开连接
     */
    public void stopBluetoothScoOn() {
        boolean isBluetoothScoOn = PocApplication.getInstance().mAudioManager.isBluetoothScoOn();
        if (isBluetoothScoOn) {
            PocApplication.getInstance().mAudioManager.setMode(AudioManager.MODE_NORMAL);
            PocApplication.getInstance().mAudioManager.setBluetoothScoOn(false);//关闭SCO通讯
            PocApplication.getInstance().mAudioManager.stopBluetoothSco(); //断开SCO
        }
    }

    /**
     * 如果扫描到上次连接过的蓝牙设备，则自动连上
     * 执行Ble设备扫描
     *
     * @param context
     */
    private void onScanBle(Context context) {
        if (isBleScaning) {
            return;
        }

        String bleMac = SPHelper.getString(SPHelper.SPKeyGlobal.KEY_BLE_MAC);
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setServiceUuids(null)
                .setDeviceName(true, "BEASUN GY2")
                .setDeviceMac(bleMac)
                .setAutoConnect(GaiaLink.checkBluetoothAddress(bleMac))//Mac地址有效时自动连接，无效时不自动连接
                .setScanTimeOut(8000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scanAndConnect(new BleScanAndConnectCallback() {
            @Override
            public void onStartConnect() {
            }

            @Override
            public void onConnectFail(BleException exception) {
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                if (bleDevice == null) {
                } else {
                }
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                if (device == null) {
                } else {
                }
            }

            @Override
            public void onScanStarted(boolean success) {
                isBleScaning = true;
            }

            @Override
            public void onScanFinished(BleDevice scanResult) {
                isBleScaning = false;
                if (scanResult == null) {
                } else {
                }
            }
        });


    }

    /**
     * Ptt键按下与放开事件
     *
     * @param isRequest true：按下
     */
    public void pttHandleTalk(boolean isRequest) {
        ALog.dTag(TAG_SCO, "PTT事件：isRequest = %s,%s", isRequest, NetworkUtils.isConnected());
        /** @modify sudf
         * @data 2017.12.20
         * @describe 按下PTT键时，可正常申请话语权，当放开PTT时，出现网络波动，会出现话语权无法释放
         */
        if (isRequest && !NetworkUtils.isConnected()) {
            ToastUtils.showToast(Utils.getApplication().getString(R.string.tip_net_error));
            return;
        }
        if (!isEnablePTT || PocService.isPhoneCalling) {
            ToastUtils.showToast("当前PTT不可用");
            return;
        }
        isBtPttPress = isRequest;
        PocService.getInstance().setPTTPressed(isBtPttPress);
        final AirSession airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().getLockedAirSession();

        /**
         * @author sudf
         * @data 2018.1.6
         * 目前基于建立SCO后播放提示音，蓝牙设备无法播放，一下为暂时解决方案：
         * 1、当前所有监听频道中无人正在对讲，则同时发起建立SCO连接和申请话语权
         * 2、当前所有监听频道中的锁定频道内有人正在讲话，则提示“嘟”提示音后拒绝话语权申请
         * 3、当前所有监听频道中无锁定频道，则提示“嘀嘀”提示音后结束话语权申请
         *
         */
        if (lockChannelTalking(airSession)) {
            if (isRequest) {
                if (airSession == null) {
                    Sound.playSound(Sound.PLAYER_CALL_ERROR, this);
                } else {
                    Sound.playSound(Sound.PLAYER_MEDIA_ERROR, this);
                }
            } else {
                stopBluetoothScoOn();
            }
            return;
        }

        BTDeviceBean bean = new BTDeviceBean();
        bean.setCurrentEvent(isRequest ? BTDeviceBean.EVENT_PTT_PREPARE : BTDeviceBean.EVENT_PTT_END);
        bean.setTarget(this.getClass(), BTService.class, "onEventBusBTDevice");
        onEventBusBTDevice(bean);
//        if (isRequest) {
////            final long startTime = System.currentTimeMillis();
////            SoundPoolUtils.getInstance().onPlay(SoundPoolUtils.KEY_SOUND_A1, new SoundPool.OnLoadCompleteListener(){
////
////                @Override
////                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
////                    ALog.dTag("timeLog", "totalTime = %s", System.currentTimeMillis() - startTime);
////                    startBluetoothScoOn();
////                }
////            });
//            Sound.playSound(Sound.PLAYER_MEDIA_OTHER_ON, this);
//            try {
//                Thread.sleep(400);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            startBluetoothScoOn();
//            PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRequest(airSession);
////            try {
////                Sound.playSound(Sound.PLAYER_MEDIA_OTHER_ON, this);
////                Thread.sleep(400);
////                startBluetoothScoOn();
////            } catch (InterruptedException e) {
////                e.printStackTrace();
////            }
//
////            Sound.playSound(Sound.PLAYER_MEDIA_OTHER_ON, this, new MediaPlayer.OnCompletionListener() {
////
////                @Override
////                public void onCompletion(MediaPlayer mp) {
////                    ALog.dTag("timeLog", "totalTime = %s", System.currentTimeMillis() - startTime);
////                    /**
////                     * @author sudf
////                     * @date 2017.9.1
////                     * bug：0000514 【睿洽对讲安卓公众版】手咪发起对讲mic通道问题
////                     * 原因分析：1、蓝牙通道相关startBluetoothScoOn 处理完之后再去准备对讲SDK的对讲流程
////                     *           与
////                     *           2、对讲SDK开始着手准备对讲时在去处理startBluetoothScoOn
////                     *           的差异
////                     * 解决方案：使用方案2会有这个bug问题，所以采用方案1
////                     */
////                    startBluetoothScoOn();
////                    PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRequest(airSession);
////                }
////            });
//
//        } else {
//            PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRelease(airSession);
//            stopBluetoothScoOn();
//        }
    }

    /**
     * 当前频道是否有人在讲话
     *
     * @param airSession
     * @return true:有
     */
    private boolean lockChannelTalking(AirSession airSession) {
        if (airSession == null) {
            return true;
        }
        Map<String, String> currentTalking = PocService.getInstance().getCurrentTalking();
        String currentChannel = airSession.getChannel().getId();
        if (!TextUtils.isEmpty(currentTalking.get(currentChannel))) {
            return true;
        }
//        Iterator iter = currentTalking.entrySet().iterator();
//        while (iter.hasNext()) {
//            Map.Entry entry = (Map.Entry) iter.next();
//            Object key = entry.getKey();
//            ALog.dTag("CurrentTalking", "key = %s,value = %s", (String) key, currentTalking.get(key));
//            if (!TextUtils.isEmpty((String) key)) {
//                return true;
//            }
//        }
        return false;
    }

    /**
     * 有线media键设备的Ptt键按下与放开事件,不判定是否是绑定的设备
     *
     * @param isRequest true：按下
     */
    public void pttTalkNormal(boolean isRequest) {
        if (!isEnablePTT) {
            ToastUtils.showToast("当前PTT不可用");
            return;
        }
        isBtPttPress = isRequest;
        PocService.getInstance().setPTTPressed(isBtPttPress);
        AirSession airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().getLockedAirSession();
        if (airSession == null) {
            if (isRequest) {
                Sound.playSound(Sound.PLAYER_CALL_ERROR, this);
            }
            return;
        }
        if (isRequest) {
            PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRequest(airSession);
        } else {
            PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRelease(airSession);
        }
    }

    /**
     * 发起PTT设备连接
     *
     * @param address
     */
    public void connectPTT(String address) {
        try {
            ALog.dTag(TAG, "address = %s", address);
            if (!GaiaLink.checkBluetoothAddress(address)) {
                ToastUtils.showToast(this, "无效的蓝牙mac地址");
                return;
            }
            mGaiaLink.connect(address);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开PTT设备连接
     */
    public void disconnectPTT() {
        try {
            ALog.dTag(TAG, "disconnectPTT ...");
            mGaiaLink.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            ALog.dTag(TAG, "profile = %s", profile);
            isEnablePTT = false;
            if (profile == BluetoothProfile.HEADSET) {
                mBluetoothHeadset = (BluetoothHeadset) proxy;
                List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
                if (devices == null || devices.size() <= 0) {
                    ToastUtils.showToast(BTService.this, "检测不到蓝牙设备，请检测是否正常连接");
                    return;
                }
                mBlueToothAddress = devices.get(0).getAddress();
                BluetoothBean bluetoothBean = new BluetoothBean();
                bluetoothBean.setCurrentEvent(BluetoothBean.EVENT_ENABLE_PTT);
                bluetoothBean.setTarget(this.getClass(), BTService.class, "onBluetoothEventBus");
                onBluetoothEventBus(bluetoothBean);
                connectPTT(mBlueToothAddress);
            }
        }

        public void onServiceDisconnected(int profile) {
            ALog.dTag(TAG, "profile = %s", profile);
            mBluetoothAdapter.closeProfileProxy(profile, mBluetoothHeadset);
            mBluetoothHeadset = null;
            disconnectPTT();
        }
    };

    /**
     * 蓝牙相关广播接收器<br>
     * 1、注册监听蓝牙sco通道状态 : AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED<br>
     * 状态key：AudioManager.EXTRA_SCO_AUDIO_STATE，状态value如下：<br>
     * {@code AudioManager.SCO_AUDIO_STATE_CONNECTED }: 连接成功<br>
     * {@code AudioManager.SCO_AUDIO_STATE_CONNECTING }: 连接中<br>
     * {@code AudioManager.SCO_AUDIO_STATE_DISCONNECTED }: 连接失败<br>
     * {@code AudioManager.SCO_AUDIO_STATE_ERROR }: 连接异常<br>
     * 2、蓝牙连接状态的广播 : BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED<br>
     * 状态key：BluetoothHeadset.EXTRA_STATE，状态value如下：<br>
     * {@code BluetoothHeadset.STATE_DISCONNECTED }: 未连接<br>
     * {@code BluetoothHeadset.STATE_CONNECTING }: 连接中<br>
     * {@code BluetoothHeadset.STATE_CONNECTED }: 连接成功<br>
     * {@code BluetoothHeadset.STATE_DISCONNECTING }:<br>
     * 3、蓝牙开关状态的广播 : BluetoothAdapter.ACTION_STATE_CHANGED
     */
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            ALog.dTag(TAG, "action = %s", action);
            if (AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED.equals(action)) //蓝牙sco状态
            {
                int scoState = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, AudioManager.SCO_AUDIO_STATE_ERROR);
                ALog.dTag(TAG, "当前蓝牙SCO状态： %s，%s", scoState, TranslateUtils.getBluetoothScoAudioStateTip(scoState));
                switch (scoState) {
                    case AudioManager.SCO_AUDIO_STATE_CONNECTED://连接成功
                        PocApplication.getInstance().mAudioManager.setBluetoothScoOn(true);
                        if (PocService.getInstance() != null) {
                            PocService.getInstance().setBluetoothScoOn(true);
                        }
                        TalkBean bean = new TalkBean();
                        bean.setCurrentEvent(TalkBean.EVENT_TALKING);
                        bean.setAirSession(PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().getLockedAirSession());
                        bean.setTarget(this.getClass(), PocService.class, "onEventBusTalk");
                        EventBus.getDefault().post(bean);
                        break;
                    case AudioManager.SCO_AUDIO_STATE_CONNECTING://连接过程
                        break;
                    case AudioManager.SCO_AUDIO_STATE_DISCONNECTED://连接失败
                    case AudioManager.SCO_AUDIO_STATE_ERROR://状态异常
                        if (PocService.getInstance() != null) {
                            PocService.getInstance().setBluetoothScoOn(false);
                        }
                    default:
                        break;
                }
            } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action))//蓝牙连接状态的广播
            {
                int headsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_CONNECTED);
                ALog.dTag(TAG, "当前蓝牙连接状态： %s，%s", headsetState, TranslateUtils.getBluetoothHeadsetStateTip(headsetState));
                switch (headsetState) {
                    case BluetoothHeadset.STATE_CONNECTED://连接成功
                        mBluetoothAdapter.getProfileProxy(getApplicationContext(), mProfileListener, BluetoothProfile.HEADSET);
//                        onScanBle(context);
                        String bleMac = SPHelper.getString(SPHelper.SPKeyGlobal.KEY_BLE_MAC);
                        LeManager.getInstance().onScanBleAndConnected(bleMac, BTService.this);
                        break;
                    case BluetoothHeadset.STATE_DISCONNECTED://未连接
                        if (isBtPttPress) {//蓝牙断开后可能ptt还没松开
                            pttHandleTalk(false);
                        }
                        stopBluetoothScoOn();
                        disconnectPTT();
                        String bleMac1 = SPHelper.getString(SPHelper.SPKeyGlobal.KEY_BLE_MAC);
                        LeManager.getInstance().onDisConnectedBle(bleMac1);
                        break;
                    case BluetoothHeadset.STATE_CONNECTING://连接中
                    case BluetoothHeadset.STATE_DISCONNECTING:
                    default:
                        break;
                }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action))//蓝牙开关状态的广播
            {
                int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
                ALog.dTag(TAG, "当前蓝牙开关状态： %s，%s", bluetoothState, TranslateUtils.getBluetoothStateTip(bluetoothState));
                switch (bluetoothState) {
                    case BluetoothAdapter.STATE_OFF:
                        ToastUtils.showToast(BTService.this, TranslateUtils.getBluetoothStateTip(BluetoothAdapter.STATE_OFF));
                        if (isBtPttPress) {//蓝牙断开后可能ptt还没松开
                            pttHandleTalk(false);
                        }
                        Sound.playSound(R.raw.sound_media_me_off, BTService.this);
                        disconnectPTT();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        ToastUtils.showToast(BTService.this, TranslateUtils.getBluetoothStateTip(BluetoothAdapter.STATE_TURNING_ON));
                        break;
                    case BluetoothAdapter.STATE_ON:
                        /**
                         * 当蓝牙开关开启时，发起设备周边设备搜索
                         * 成功搜索到设备时，会接收到BluetoothDevice.ACTION_FOUND广播
                         */
                        if (!mBluetoothAdapter.isDiscovering()) {
                            mBluetoothAdapter.startDiscovery();
                            ToastUtils.showToast(BTService.this, "设备搜索中");
                        }
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        ToastUtils.showToast(BTService.this, TranslateUtils.getBluetoothStateTip(BluetoothAdapter.STATE_TURNING_OFF));
                        break;
                    default:
                        break;
                }
            } else if (BluetoothDevice.ACTION_FOUND.equals(action))//用BroadcastReceiver来取得搜索结果
            {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BluetoothDeviceBean bean = new BluetoothDeviceBean();
                bean.setName(device.getName());
                bean.setAddress(device.getAddress());
                if (device.getBondState() == BluetoothDevice.BOND_NONE
                        && mBlueToothAddress != null && mBlueToothAddress.equals(device.getAddress())) {
                    ALog.dTag(TAG, "bondState === " + device.getBondState() + "deviceName = " + bean.getName() + ",deviceAddress = " + bean.getAddress());
                    try {
                        //通过工具类ClsUtils,调用createBond方法
                        BluetoothUtils.createBond(device.getClass(), device);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    /**
     * GaiaLink蓝牙协议回调的Handler
     */
    Handler mGaiaLinkReceiveHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            //UNHANDLED, CONNECTED, ERROR, DEBUG, DISCONNECTED;
            ALog.dTag(TAG, "currentEvent = %s", msg.what);
            switch (msg.what) {
                case 0://GaiaLink.Message.UNHANDLED
                    gaiaLink_unhandled(msg);
                    break;
                case 1://GaiaLink.Message.CONNECTED：蓝牙手咪连接成功
                    gaiaLinka_connected();
                    break;
                case 2://GaiaLink.Message.ERROR
                    //处理蓝牙Mac搜索结果
                    boolean isBound = false;
                    if (msg.obj instanceof IOException) {
                        break;
                    }
                    String backJson = (String) msg.obj;
                    if (TextUtils.isEmpty(backJson)) {
                        break;
                    }
                    try {
                        JSONObject json = new JSONObject(backJson);
                        if (!json.getString("code").equals("200")) {
                            Toast.makeText(BTService.this, "查询蓝牙绑定失败，请检查您的网络", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        JSONObject data = json.getJSONObject("data");
                        JSONArray bluetooth = data.getJSONArray("bluetooth");
                        for (int i = 0; i < bluetooth.length(); i++) {
                            if (bluetooth.getJSONObject(i).getString("mac").equals(mBlueToothAddress)) {
                                isBound = true;
                                connectPTT(mBlueToothAddress);
                                break;
                            }
                        }
                        if (!isBound) {
                            Toast.makeText(BTService.this, "您的蓝牙还未进行绑定，请先绑定才能连接使用", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 3://GaiaLink.Message.DEBUG
                case 4://GaiaLink.Message.DISCONNECTED
                default:
                    break;

            }
        }

        /**
         * 蓝牙手咪设备连接成功
         */
        private void gaiaLinka_connected() {
            try {
                mGaiaLink.registerNotification(Gaia.EventId.USER_ACTION);
                //蓝牙连上提示音
//                Sound.playSound(R.raw.sound_call_dial,true,BTService.this);
                Toast.makeText(BTService.this, "蓝牙已连接", Toast.LENGTH_SHORT).show();
                //isPttConnect = true;
            } catch (Exception localException) {
//                Toast.makeText(BTService.this, "PTT is disconnect!", Toast.LENGTH_SHORT).show();
                //isPttConnect = false;
            }
        }

        /**
         * GaiaLink.Message.UNHANDLED处理
         * 连接蓝牙手咪，手咪设备的Handler行为回调
         * {@code gaiaCommand.getShort(1) == 24768} 按下<br>
         * {@code gaiaCommand.getShort(1) == 24769} 放开<br>
         * {@code gaiaCommand.getShort(1) == 24624} 定时接收，行为未知<br>
         * @param msg
         */
        private void gaiaLink_unhandled(Message msg) {
            GaiaCommand gaiaCommand = (GaiaCommand) msg.obj;
            if (gaiaCommand.getShort(1) == 24768) {
                pttHandleTalk(true);
            } else if (gaiaCommand.getShort(1) == 24769) {
                pttHandleTalk(false);
            }
        }
    };

    @Override
    public void onBlePttCallback(int type) {
        if (type == 1) {
            Talk2PttBean bean = new Talk2PttBean();
            bean.setTarget(this.getClass(), BTService.class, "onEventBusTalkStatus");
            bean.setCurrentEvent(Talk2PttBean.EVENT_BLE_TALK);
            EventBus.getDefault().post(bean);
        } else if (type == 0) {
            Talk2PttBean bean = new Talk2PttBean();
            bean.setTarget(this.getClass(), BTService.class, "onEventBusTalkStatus");
            bean.setCurrentEvent(Talk2PttBean.EVENT_BLE_TALK_RELEASE);
            EventBus.getDefault().post(bean);
            Sound.playSound(Sound.PLAYER_MEDIA_ME_OFF, this);
        }
    }

    public class LocalBinder extends Binder {
        public BTService getService() {
            return BTService.this;
        }
    }


    /**
     * EVENT_PTT_PREPARE：按下PTT时，准备对讲，用于区分话语权申请与SCO的同、异步进行
     * EVENT_PTT_PREPARE_SYNC_SCO_AND_REQUEST：
     *
     * @param bean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusBTDevice(BTDeviceBean bean) {
        if (bean == null || !bean.isTarget(this.getClass())) {
            return;
        }
        AirSession airSession = PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().getLockedAirSession();
        switch (bean.getCurrentEvent()) {
            case BTDeviceBean.EVENT_SCO_OPEN:
                startBluetoothScoOn();
                break;
            case BTDeviceBean.EVENT_SCO_CLOSE:
                stopBluetoothScoOn();
                break;
            case BTDeviceBean.EVENT_PTT_PREPARE:
                BTDeviceBean prepareBean = new BTDeviceBean();
                prepareBean.setCurrentEvent(BTDeviceBean.EVENT_PTT_PREPARE_SYNC_SCO_AND_REQUEST);
                prepareBean.setTarget(this.getClass(), BTService.class, "onEventBusBTDevice");
                onEventBusBTDevice(prepareBean);
                break;
            case BTDeviceBean.EVENT_PTT_PREPARE_SYNC_SCO_AND_REQUEST:
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRequest(airSession);
                Sound.playSound(Sound.PLAYER_MEDIA_ME_ON, this);
                try {
                    Thread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                BTDeviceBean talkBean = new BTDeviceBean();
                talkBean.setCurrentEvent(BTDeviceBean.EVENT_SCO_OPEN);
                talkBean.setTarget(this.getClass(), BTService.class, "onEventBusBTDevice");
                onEventBusBTDevice(talkBean);
                break;
            case BTDeviceBean.EVENT_PTT_PREPARE_ASYN_SCO_AFTER_REQUEST:
                break;
            case BTDeviceBean.EVENT_PTT_END:
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().talkRelease(airSession);
                BTDeviceBean talkEndBean = new BTDeviceBean();
                talkEndBean.setCurrentEvent(BTDeviceBean.EVENT_SCO_CLOSE);
                talkEndBean.setTarget(this.getClass(), BTService.class, "onEventBusBTDevice");
                onEventBusBTDevice(talkEndBean);
                break;
            default:
                break;
        }
    }


}
